package com.ls.lserp.modules.order.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.order.service.BigcargoOrderService;
import com.ls.lserp.modules.produce.entity.ProduceLicense;
import com.ls.lserp.modules.produce.entity.ProduceNotice;
import com.ls.lserp.modules.produce.service.ProduceLicenseService;
import com.ls.lserp.modules.sys.utils.UserUtils;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

/**
 * @author 许天航
 * @ClassName: QuotationController
 * @Description:
 * @date 2017年01月09日
 */

@Controller
@RequestMapping(value = "${adminPath}/bigcargo/order/")
public class BigcargoOrderController extends BaseController {

    @Autowired
    private BigcargoOrderService bigcargoOrderService;
    @Autowired
	private ProduceLicenseService produceLicenseService;
    @Autowired
    Configuration freemarkerConfiguration;

    @ModelAttribute
    public BigcargoOrder get(@RequestParam(required = false) String id) {
        // 判断id是否为空
        if (StringUtils.isNotBlank (id)) {
            // 执行查询语句 查询基本信息
            return bigcargoOrderService.findByID (Long.parseLong (id));
        } else {
            // 若为空，实例化
            return new BigcargoOrder ();
        }
    }

    /**
     * 大货订单一览画面
     *
     * @return
     */
    @RequestMapping(value = {""})
    public String bigcargoOrder(Model model) {
    	List <ProduceLicense> groupList = produceLicenseService.findGroupList ();
        model.addAttribute ("groupList", groupList);
        return "modules/order/bigcargoOrder";
    }

    /**
     * 拼接一览画面
     *
     * @param values
     * @return
     */
    @RequiresPermissions("bigcargo:order:view")
    @RequestMapping(value = {"searchList"})
    @ResponseBody
    public String searchList(BigcargoOrder bigcargoOrder, HttpServletRequest request, HttpServletResponse response,
                             Model model, String[] values) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute ("listNames", "bigcargoOrder");
        // 画面取得的检索项目
        String contractNO = bigcargoOrder.getContractNO ();
        String ognizationName = bigcargoOrder.getOgnizationName ();
        //String orderTypeCD = bigcargoOrder.getOrderTypeCD();
        String ulSelected = bigcargoOrder.getUlSelected ();
        // 待审核
        if ("2".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_10";
        // 审核通过
        } else if ("1".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_20";
        // 审核拒绝
        } else if ("0".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_30";
        // 生产中
        } else if ("3".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_20";
            bigcargoOrder.setProduceStatus("0");
        // 生产完成
        } else if ("4".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_20";
            bigcargoOrder.setProduceStatus("1");
        }
        bigcargoOrder.setUlSelected (ulSelected);
        // 班组
        String userGroupID = bigcargoOrder.getUserGroupId();
        // 开始日期
        String dateStart = bigcargoOrder.getDateStart ();
        // 截止日期
        String dateEnd = bigcargoOrder.getDateEnd ();
        // 拼接字符串供分页使用
        String searchParam = "&contractNO=" + contractNO + "&ognizationName=" + ognizationName + "&ulSelected=" + ulSelected + "&userGroupID=" + userGroupID + "&dateStart=" + dateStart + "&dateEnd=" + dateEnd;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        Page <BigcargoOrder> page = bigcargoOrderService.findBigcargoOrderList (new Page <BigcargoOrder> (request, response),
                bigcargoOrder);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("orderList", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("bigcargoOrderList.ftl"), map);
        listMap.put ("bigcargoOrder", strHtml);
        listMap.put ("page", page.getHtml ());
        // ajax返回结果
        return renderString (response, listMap);
    }

    /**
     * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     *
     * @param filePath
     * @return html
     */
    public String readTxtFile(String filePath) {
        String strHtml = "";
        try {
            String encoding = "UTF-8";
            File file = new File (filePath);
            // 判断文件是否存在
            if (file.isFile ()) {
                InputStreamReader read = new InputStreamReader (
                        // 考虑到编码格式
                        new FileInputStream (file), encoding);
                BufferedReader bufferedReader = new BufferedReader (read);
                String lingText = null;
                while ((lingText = bufferedReader.readLine ()) != null) {
                    strHtml += lingText;
                }
                read.close ();
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return strHtml;
    }

    /**
     * 创建大货订单信息窗口
     *
     * @return
     */

    @RequestMapping(value = "createBigcargoOrder")
    public String createBigcargoOrder(BigcargoOrder bigcargoOrder, HttpServletRequest request, HttpServletResponse response,
                                      Model model) {
        List <BigcargoOrder> customerList = bigcargoOrderService.findCustomerList ();
        bigcargoOrder.setOrderStyleList (customerList);
        bigcargoOrder.setCreateBy (UserUtils.getUser ());
        model.addAttribute ("bigcargoOrder", bigcargoOrder);
        return "modules/order/bigcargoOrderCreate";
    }

    /**
     * 编辑大货订单信息窗口
     *
     * @return
     */
    @RequiresPermissions("bigcargo:order:view")
    @RequestMapping(value = "editBigcargoOrder")
    public String editBigcargoOrder(BigcargoOrder bigcargoOrder, HttpServletRequest request, HttpServletResponse response,
                                    Model model) {
        bigcargoOrder = bigcargoOrderService.findBigcargoOrder (bigcargoOrder);
        model.addAttribute ("bigcargoOrder", bigcargoOrder);
        return "modules/order/bigcargoOrderCreate";
    }

    /**
     * 查看一条大货订单信息
     *
     * @return
     */
    @RequiresPermissions("bigcargo:order:view")
    @RequestMapping(value = "viewBigcargoOrder")
    public String viewBigcargoOrder(BigcargoOrder bigcargoOrder, HttpServletRequest request, HttpServletResponse response,
                                    Model model) {
        bigcargoOrder = bigcargoOrderService.findBigcargoOrder (bigcargoOrder);
        model.addAttribute ("bigcargoOrder", bigcargoOrder);
        return "modules/order/bigcargoOrderShow";
    }

    /**
     * 设置颜色尺码数量
     *
     * @return
     */
    @RequiresPermissions("bigcargo:order:view")
    @RequestMapping(value = "setColorQuantity")
    public String setColorQuantity(BigcargoOrder bigcargoOrder, Model model) {
        String index = bigcargoOrder.getIndex ();
        String realIndex = bigcargoOrder.getRealIndex ();
        String auditStatus = bigcargoOrder.getStatus();
        bigcargoOrder = bigcargoOrderService.getStyle (bigcargoOrder);
        bigcargoOrder.setIndex (index);
        bigcargoOrder.setRealIndex (realIndex);
        bigcargoOrder.setStatus(auditStatus);
        model.addAttribute ("bigcargoOrder", bigcargoOrder);
        return "modules/order/bigcargoOrderCreate2";
    }

    /**
     * 款式id获取颜色尺码数量
     *
     * @return
     */
    @RequiresPermissions("bigcargo:order:view")
    @RequestMapping(value = "findColorQuantity")
    public String findColorQuantity(BigcargoOrder bigcargoOrder, HttpServletResponse response) {
        bigcargoOrder = bigcargoOrderService.getStyle (bigcargoOrder);
        return renderString (response, bigcargoOrder.getBigcargoOrderList ());

    }

    /**
     * 获取图片集
     *
     * @return
     */
    @RequiresPermissions("bigcargo:order:view")
    @RequestMapping(value = "findImageList")
    @ResponseBody
    public String findImageList(BigcargoOrder bigcargoOrder, HttpServletRequest request, HttpServletResponse response,
                                Model model) {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        Map <String, Object> map = new HashMap <String, Object> ();
        String allFlie = bigcargoOrder.getStyleFile ();
        String imageHtml = "";
        BigcargoOrder bigStyleObj = bigcargoOrderService.getStyle (bigcargoOrder);
        // 款式图片list生成
        List <BigcargoOrder> imageListTemp = bigStyleObj.getStyleFileList ();
        map.put ("imageList", imageListTemp);
        map.put ("allFlie", allFlie);
        // 生成款式图片的HTML
        imageHtml = createHtml (map, "imageUrlList.ftl");
        listMap.put ("imageListHtml", imageHtml);
        return renderString (response, listMap);

    }

    /**
     * @return HTML
     * @Title: 生成HTML
     */
    public String createHtml(Map <String, Object> map, String fileName) {
        String tempHtml = "";
        try {
            tempHtml = FreeMarkerTemplateUtils.processTemplateIntoString (freemarkerConfiguration.getTemplate (fileName),
                    map);
        } catch (Exception e) {
            return tempHtml;
        }
        return tempHtml;
    }

    /**
     * 创建编辑保存仓库信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("bigcargo:order:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(BigcargoOrder bigcargoOrder, HttpServletResponse response) throws ResourceException {
        // 判断id是否为null （判断新建或修改）
        if (bigcargoOrder.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            BigcargoOrder bigcargoOrderNew = get (bigcargoOrder.getId ().toString ());
            // 判断数据是否删除
            if (bigcargoOrderNew == null || BaseEntity.DEL_FLAG_DELETE.equals (bigcargoOrderNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
            // 排他处理
            if (bigcargoOrder.getVersion () == get (bigcargoOrder.getId ().toString ()).getVersion ()) {
                // 版本号加1
                bigcargoOrder.setVersion (bigcargoOrder.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }
        // 保存数据
        bigcargoOrderService.saveBigcargoOrder (bigcargoOrder);
        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));
    }

    /**
     * 审核页面
     *
     * @param bigcargoOrder
     * @param model
     * @return
     */
    @RequiresPermissions("bigcargo:order:audit")
    @RequestMapping(value = "audit")
    public String audit(BigcargoOrder bigcargoOrder, Model model) {
        // 履历一览取得
        AuditInfo auditInfo = new AuditInfo ();
        // id
        auditInfo.setAuditRelateId (bigcargoOrder.getId ());
        // 阶段
        auditInfo.setAuditPhaseCd (ResourcesUtil.getConfig ("audit_phase_contract"));
        AuditInfo resultInfo = bigcargoOrderService.findAuditInfo (auditInfo);
        resultInfo.setAuditRelateId (bigcargoOrder.getId ());
        resultInfo.setAuditRelateNo (bigcargoOrder.getContractNO ());
        resultInfo.setAuditPhaseCd (ResourcesUtil.getConfig ("audit_phase_contract"));
        // 将实体类值赋给mvc model层返回jsp页面
        model.addAttribute ("auditInfo", resultInfo);

        // 返回页面地址
        return "modules/order/auditInfo";
    }

    /**
     * 保存履历信息
     *
     * @param auditInfo
     * @param request
     * @param model
     * @param response
     * @return
     * @throws ResourceException
     */
    @RequiresPermissions("bigcargo:order:edit")
    @RequestMapping(value = "saveAudit")
    @ResponseBody
    public String saveAudit(AuditInfo auditInfo, HttpServletRequest request, Model model, HttpServletResponse response, HttpSession session) throws ResourceException {
        // 是否需要更新样品需求状态
        boolean isUpdateStatus = false;
        // 判断数据是否删除
        BigcargoOrder bigcargoOrder = get (Long.toString (auditInfo.getAuditRelateId ()));
        // 判断数据是否删除
        if (bigcargoOrder.getContractNO () == null || BaseEntity.DEL_FLAG_DELETE.equals (bigcargoOrder.getDeleteFlag ())) {
            // 返回提示信息
            return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }
        // 审核结果已经通过,返回错误提示信息
        AuditInfo pAuditResult = new AuditInfo ();
        pAuditResult.setAuditPhaseCd (auditInfo.getAuditPhaseCd ());
        pAuditResult.setAuditRelateId (auditInfo.getAuditRelateId ());
        if (bigcargoOrderService.getAuditResult (pAuditResult) > 0) {
            // 返回提示信息
            return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }
        // 保存样品数据
        bigcargoOrderService.saveAuditInfo (auditInfo, isUpdateStatus);
        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("audit_ok_msg")));
    }
}